﻿using System;
using System.Data;
using System.Configuration;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Solely
{
    /// <summary>
    /// 水印处理
    /// </summary>
    public class ImageWater
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strFilePath"></param>
        public ImageWater(string strFilePath)
        {
            this._oldimage = strFilePath;
        }

        #region attribute
        private string _folder;
        private int _thumbWidth = 180;
        private int _thumbHeight = 150;
        private bool _iswatermark = true;
        private string _watermarktype = "img";
        private string _imgurl;
        private string _fonttext = "websen";
        private string _fontfamily = "新宋体";
        private string _fontcolor = "#ffffff";
        private float _fontsize = 36;
        private int _trans;
        private int _quality;
        private string _pos = "br";
        private int _posX;             //水印起始X轴
        private int _posY;             //水印起始Y轴
        private string _oldimage;      //上传图片的路径
        private string _newimage = "";   //新图片路径
        private string _tnewimage;     //缩略图路劲
        private string _filename;      //图片文件名称
        private string _absoldimage;
        private string _folders;       
        /// <summary>
        /// 缩略图相对路径
        /// </summary>
        public string ThumbImage
        {
            get { return _folders + "t_" + _filename+_absoldimage.Substring(_absoldimage.LastIndexOf(".")+1); }
        }

        /// <summary>
        /// 大图地址
        /// </summary>
        public string ImageUrl
        {
            get { return _folders + "m_" + _filename+_absoldimage.Substring(_absoldimage.LastIndexOf(".")+1); }
        }

        #endregion

        #region method
        /// <summary>
        /// 添加水印（外部调用）
        /// </summary>
        /// <returns></returns>
        public bool Watermark()
        {
            try
            {
                initialize();
                //加水印并上传
                if (_iswatermark)
                {
                    if (!_oldimage.EndsWith("gif"))
                    {
                        if (_watermarktype == "txt") //文字水印
                        {
                            txtWoter();
                        }
                        else  //图片水印
                        {
                            imgWater();
                        }
                        MakeThumbnail();
                    }
                    else
                    {
                        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(_absoldimage);                        
                        bitmap.Save(_newimage);
                        bitmap.Save(_tnewimage);
                    }
                }
                else {
                    PicSized(_absoldimage, _newimage,2);
                    MakeThumbnail();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 初始化设置
        /// </summary>
        private void initialize()
        {
            Base.XMLProcess xp = new Base.XMLProcess("xml/ImageWater.xml");
            this._folder = xp.Read("/param/folder");
            //this.txtFiletype.Text = xp.Read("/param/filetype");
            //this.txtFilesize.Text = xp.Read("/param/filesize");
            this._thumbWidth = int.Parse(xp.Read("/param/thumbWidth"));
            this._thumbHeight = int.Parse(xp.Read("/param/thumbHeight"));
            this._iswatermark = Convert.ToBoolean(xp.Read("/param/iswatermark"));
            this._watermarktype = xp.Read("/param/watemarktype");
            this._imgurl = System.Web.HttpContext.Current.Server.MapPath("~" + xp.Read("/param/imgurl"));
            this._fonttext = xp.Read("/param/fonttext");
            this._fontfamily = xp.Read("/param/fontfamily");
            this._fontcolor = xp.Read("/param/fontcolor");
            this._fontsize = int.Parse(xp.Read("/param/fontsize"));
            this._trans = int.Parse(xp.Read("/param/trans"));
            this._quality = int.Parse(xp.Read("/param/quality"));
            this._pos = xp.Read("/param/pos");
            this._absoldimage = System.Web.HttpContext.Current.Server.MapPath(_oldimage);
            this._folders = _oldimage.Substring(0, _oldimage.LastIndexOf("/") + 1);
            this._filename = _absoldimage.Substring(_absoldimage.LastIndexOf("\\") + 1, _absoldimage.LastIndexOf(".") - _absoldimage.LastIndexOf("\\"));
            string sFile = _absoldimage.Substring(_absoldimage.LastIndexOf("\\") + 1, _absoldimage.LastIndexOf(".") - _absoldimage.LastIndexOf("\\") - 1);
            this._newimage = _absoldimage.Substring(0, _absoldimage.LastIndexOf("\\") + 1) + "m_" + sFile + _absoldimage.Substring(_absoldimage.LastIndexOf("."));
            this._tnewimage = _absoldimage.Substring(0, _absoldimage.LastIndexOf("\\") + 1) + "t_" + sFile + _absoldimage.Substring(_absoldimage.LastIndexOf("."));

        }


        /// <summary>
        /// 添加文字水印
        /// </summary>
        /// <returns></returns>
        private string txtWoter()
        {
            System.Drawing.Image image;
            //if (strFileType == "image/bmp") //bmp图片格式
            if (true)
                image = System.Drawing.Bitmap.FromFile(_absoldimage);
            else
                image = System.Drawing.Image.FromFile(_absoldimage);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);           
            _posX = 5;
            _posY = 5;
            //将图片绘制到graphics中
            g.DrawImage(image, 0, 0, image.Width, image.Height);

            //设置文字的属性
            System.Drawing.Font f = new System.Drawing.Font(_fonttext, _fontsize, System.Drawing.GraphicsUnit.Pixel);
            //设置字体的颜色
            System.Drawing.Color customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Black);
            switch (_fontcolor.ToLower())
            {
                case "red":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Red);
                    break;
                case "yellow":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Yellow);
                    break;
                case "orange":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Orange);
                    break;
                case "green":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Red);
                    break;
                case "blue":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Blue);
                    break;
                case "white":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.White);
                    break;
                case "cyan":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Cyan);
                    break;
                case "pink":
                    customColor = System.Drawing.Color.FromArgb((int)(_trans / 100) * 255, System.Drawing.Color.Pink);
                    break;
                default:
                    break;
            }
            System.Drawing.Brush b = new System.Drawing.SolidBrush(customColor);

            System.Drawing.StringFormat fm = new System.Drawing.StringFormat();
            SetPos(fm);

            //设置双三次的高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //写字
            g.DrawString(_fonttext, f, b, new System.Drawing.RectangleF(0, 0, image.Width, image.Height), fm);
            //释放graphics
            g.Dispose();

            //保存加上水印的图片
            image.Save(_newimage);

            //释放image
            image.Dispose();

            return "";
        }


        /// <summary>
        /// 设置水印的X、Y轴
        /// </summary>
        private void SetPos(System.Drawing.StringFormat fm)
        {
            switch (_pos.ToLower())
            {
                case "tl":     //水印放置左上角
                    fm.Alignment = System.Drawing.StringAlignment.Near;
                    fm.LineAlignment = System.Drawing.StringAlignment.Near;
                    break;
                case "tm":    //水平居中垂直顶部
                    fm.Alignment = System.Drawing.StringAlignment.Center;
                    fm.LineAlignment = System.Drawing.StringAlignment.Near;
                    break;
                case "tr":           //右上角
                    fm.Alignment = System.Drawing.StringAlignment.Far;
                    fm.LineAlignment = System.Drawing.StringAlignment.Near;
                    break;
                case "ml":        //垂直居中水平靠左
                    fm.Alignment = System.Drawing.StringAlignment.Near;
                    fm.LineAlignment = System.Drawing.StringAlignment.Center;
                    break;
                case "mm":         //居中
                    fm.Alignment = System.Drawing.StringAlignment.Center;
                    fm.LineAlignment = System.Drawing.StringAlignment.Center;
                    break;
                case "mr":        //垂直居中水平靠右
                    fm.Alignment = System.Drawing.StringAlignment.Far;
                    fm.LineAlignment = System.Drawing.StringAlignment.Center;
                    break;
                case "bl":        //左下角
                    fm.Alignment = System.Drawing.StringAlignment.Near;
                    fm.LineAlignment = System.Drawing.StringAlignment.Far;
                    break;
                case "bm":        //水平居中垂直底部
                    fm.Alignment = System.Drawing.StringAlignment.Center;
                    fm.LineAlignment = System.Drawing.StringAlignment.Far;
                    break;
                default:      //水印放置右下角
                    fm.Alignment = System.Drawing.StringAlignment.Far;
                    fm.LineAlignment = System.Drawing.StringAlignment.Far;
                    break;
            }
        }


        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <returns></returns>
        private string imgWater()
        {

            System.Drawing.Image image = System.Drawing.Image.FromFile(_absoldimage);
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_imgurl);

            System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();
            System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap();
            colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0);
            System.Drawing.Imaging.ColorMap[] remapTable = { colorMap };
            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            float[][] colorMatrixElements = { 
           new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
           new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
           new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
           new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},
           new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
        };
            colorMatrixElements[3][3] = (float)_trans / 100;
            System.Drawing.Imaging.ColorMatrix wmColorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);
            imageAttributes.SetColorMatrix(wmColorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);

            double bl;
            if ((image.Width > copyImage.Width * 4) && (image.Height > copyImage.Height * 4))
            {
                bl = 1;
            }
            else if ((image.Width > copyImage.Width * 4) && (image.Height < copyImage.Height * 4))
            {
                bl = Convert.ToDouble(image.Height / 4) / Convert.ToDouble(copyImage.Height);
            }
            else if ((image.Width < copyImage.Width * 4) && (image.Height > copyImage.Height * 4))
            {
                bl = Convert.ToDouble(image.Width / 4) / Convert.ToDouble(copyImage.Width);
            }
            else
            {
                if ((copyImage.Width * image.Height) > (copyImage.Height * image.Width))
                {
                    bl = Convert.ToDouble(image.Height / 4) / Convert.ToDouble(copyImage.Height);
                }
                else
                {
                    bl = Convert.ToDouble(image.Width / 4) / Convert.ToDouble(copyImage.Width);
                }

            }

            int WatermarkWidth = Convert.ToInt32(copyImage.Width * bl);
            int WatermarkHeight = Convert.ToInt32(copyImage.Height * bl);

            setPos(image, WatermarkWidth, WatermarkHeight);
            //WatermarkWidth = copyImage.Width;
            //WatermarkHeight = copyImage.Height;


            g.DrawImage(copyImage, new System.Drawing.Rectangle(_posX, _posY, WatermarkWidth, WatermarkHeight), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes);
            g.Dispose();
            image.Save(_newimage,ImageFormat.Jpeg);
            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="image"></param>
        /// <param name="xpos"></param>
        /// <param name="ypos"></param>
        private void setPos(System.Drawing.Image image, int xpos, int ypos)
        {
            switch (_pos)
            {
                case "tl":
                    _posX = 10;
                    _posY = 10;
                    break;
                case "tm":
                    _posX = (image.Width - xpos) / 2;
                    _posY = 10;
                    break;
                case "tr":
                    _posX = image.Width - xpos - 10;
                    _posY = 10;
                    break;
                case "ml":
                    _posX = 10;
                    _posY = (image.Height - ypos) / 2; ;
                    break;
                case "mm":
                    _posX = (image.Width - xpos) / 2;
                    _posY = (image.Height - ypos) / 2;
                    break;
                case "mr":
                    _posX = image.Width - xpos - 10;
                    _posY = (image.Height - ypos) / 2;
                    break;
                case "bl":
                    _posX = 10;
                    _posY = (image.Height - ypos);
                    break;
                case "bm":
                    _posX = (image.Width - xpos) / 2;
                    _posY = image.Height - ypos - 10;
                    break;
                default:
                    _posX = image.Width - xpos - 10;
                    _posY = image.Height - ypos - 10;
                    break;
            }
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <returns>返回缩略图路径</returns>
        public void MakeThumbnail()
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(_absoldimage);
            string thumbPath = _newimage;
            int toWidth = _thumbWidth;
            int toHeight = _thumbHeight;
            string wz = "";
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;


            //设置缩略图的高和宽，如果有一个值小于等于0的话，则按照另一值缩放该值
            if (toWidth > 0)
            {
                if (toHeight <= 0)
                {
                    toHeight = originalImage.Height * _thumbWidth / originalImage.Width;
                }
            }
            else
            {
                if (toHeight > 0)
                {
                    toWidth = originalImage.Width * _thumbHeight / originalImage.Height;
                }
                else
                {
                    return;
                }
            }

            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(toWidth, toHeight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置双三次的高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            //g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, toWidth, toHeight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                 bitmap.Save(_tnewimage, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
         /// <summary> 
         ///  不加水印时 放大缩小图片尺寸 
         /// </summary> 
         /// <param name="picPath"></param> 
         /// <param name="reSizePicPath"></param> 
         /// <param name="iSize"></param> 
         /// <param name="format"></param> 
        public void PicSized(string picPath, string reSizePicPath, int iSize)
        {
            Bitmap originBmp = new Bitmap(picPath);
            int w = originBmp.Width * iSize;
            int h = originBmp.Height * iSize;
            Bitmap resizedBmp = new Bitmap(w, h);
            Graphics g = Graphics.FromImage(resizedBmp);
            //设置高质量插值法   
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度   
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            //消除锯齿 
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.DrawImage(originBmp, new Rectangle(0, 0, w, h), new Rectangle(0, 0, originBmp.Width, originBmp.Height), GraphicsUnit.Pixel);
            if (!_oldimage.EndsWith("gif"))
                resizedBmp.Save(reSizePicPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            else
                resizedBmp.Save(reSizePicPath, System.Drawing.Imaging.ImageFormat.Gif);
            g.Dispose();
            resizedBmp.Dispose();
            originBmp.Dispose();
        }
 

        #endregion    
             
    }
}